<template>
  <div>
    <el-card style="margin-bottom: 20px" >
      <CategorySelect @getCategory="getCategory" :show="!isShowTable" />
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          @click="addAttr"
          :disabled="!categoryId3"
          type="primary"
          icon="el-icon-plus"
          style="margin-bottom: 10px"
          >添加属性</el-button
        >
        <el-table :data="attrList" border style="width: 100%">
          <el-table-column type="index" label="序号" align="center" width="180">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="180">
          </el-table-column>
          <el-table-column prop="attrValueList" label="属性值列表">
            <template slot-scope="{ row }">
              <el-tag
                style="margin-right: 20px"
                type="success"
                v-for="attr in row.attrValueList"
                :key="attr.id"
                >{{ attr.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="属性值列表" width="180" label="操作">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!isShowTable">
        <el-form inline ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-table
          border
          :data="attrInfo.attrValueList"
          style="width: 100%; margin: 20px 0"
        >
          <el-table-column align="center" type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                :ref="$index"
                v-if="row.flag"
                v-model="row.valueName"
                placeholder="请输入属性值"
                size="small"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template slot-scope="{$index}">
              <el-popconfirm title="这是一段内容确定删除吗" @onConfirm="deleteAttrValue($index)">
                <el-button type="danger" size="mini" icon="el-icon-delete" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrInfo.attrValueList.length<1" @click="AddorUpdateAttr">保存</el-button>
        <el-button type="primary" plain @click="isShowTable = true"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入lodash当中的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      //对象存储顺序是无序的
      categoryId1: "",
      categoryId2: "",
      categoryId3: "",
      attrList: [],
      //控制是否显示表格
      isShowTable: true,
      //收集和修改属性使用
      attrInfo: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    //自定义事件回调
    getCategory({ categoryId, level }) {
      if (level === 1) {
        this.categoryId1 = categoryId;
        //一级变化 二级 三级清空
        this.categoryId2 = "";
        this.categoryId3 = "";
      } else if (level === 2) {
        this.categoryId2 = categoryId;
        //清空三级
        this.categoryId3 = "";
      } else if (level == 3) {
        this.categoryId3 = categoryId;
        //代表三级分类的id有了向后台发送请求
        this.getAttrList();
      }
    },
    //获取品牌属性
    async getAttrList() {
      const { categoryId1, categoryId2, categoryId3 } = this;
      const result = await this.$API.attr.getAttrInfo(
        categoryId1,
        categoryId2,
        categoryId3
      );
      if (result.code === 200) {
        this.attrList = result.data;
      }
    },
    //添加属性
    addAttr() {
      this.isShowTable = false;
      //清除数据
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.categoryId3,
        categoryLevel: 3,
      };
    },
    updateAttr(row) {
      this.isShowTable = false;
      //将选中的属性赋值给attr
      //由于数据结构中存在对象里面套数组,数组里面又套对象,因此需要使用深拷贝解决这个类问题
      this.attrInfo = cloneDeep(row);
      //在修改某一个属性,将相应的属性值元素添加上flag标记
      this.attrInfo.attrValueList.forEach((item) => {
        //这样写也可以给属性值添加flag字段,但是会发现视图不会跟着变化,因为flag不是响应式数据
        //vue无法探测普通的新增property
        //item.flag = false
        //必须这样写
        this.$set(item, "flag", false);
      });
    },
    //添加属性值回调
    addAttrValue() {
      //向属性值的数组中添加元素
      this.attrInfo.attrValueList.push({
        //添加属性给服务器的id为undefined
        attrId: this.attrInfo.id, //对于修改某一个属性时候,可以在已有的属性基础上新增新的属性
        valueName: "",
        flag: true, //给每一个对象添加一个标志用于切换查看与编辑模式
      });
      this.$nextTick(() => {
        this.$$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    toLook(row) {
      if (row.valueName.trim() == "") {
        this.$message("输入不能为空");
        return;
      }
      const isRepat = this.attrInfo.attrValueList.some((item) => {
        //判断最后一次添加和前面是否相同
        if (row !== item) {
          return row.valueName == item.valueName;
        }
      });
      if (isRepat) {
        this.$message("不能输入相同的属性值");
        return;
      }
      row.flag = false;
    },
    toEdit(row, index) {
      row.flag = true;
      //获取input实现自动聚焦
      //需要注意,点击span的时候变为编辑模式,对于浏览器而言,页面的重排是要耗费时间
      //因此不可能一点击立马获得input
      //$nextTick,当节点渲染完毕会执行一次,此时input已经渲染完毕
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    deleteAttrValue(index){
     this.attrInfo.attrValueList.splice(index,1);
    },
    //保存按钮
    async AddorUpdateAttr(){
      //如果用户添加了很多属性值,且属性值为空的不应该提交给服务器
      //提交给服务器的数据当中不应该出现flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item=>{
        //过滤掉属性不为空
        if(item.valueName){
          //删除掉flag属性
          delete item.flag
          return true
        }
      })
      try {
         await this.$API.attr.reqAddorUpdateAttr(this.attrInfo)
         this.isShowTable = true
         this.$message({type:'success',message:'保存成功'})
         this.getAttrList()
      } catch (error) {
        this.$message('保存失败')
      }

    }
  },
};
</script>

<style></style>
